<template>
  <div class="course-detail-page">
    <!-- 加载状态 -->
    <div class="loading-state" v-if="loading">
      <div class="loading-spinner"></div>
      <h3>正在为您准备课程详情</h3>
      <p>请稍候，精彩内容即将呈现...</p>
      <div class="loading-progress">
        <div class="loading-bar" :style="{ width: loadingProgress + '%' }"></div>
      </div>
    </div>

    <!-- 错误状态 -->
    <div class="error-state" v-else-if="errorMessage">
      <i class="fa fa-exclamation-circle"></i>
      <h3>课程加载遇到问题</h3>
      <p>{{ errorMessage }}</p>
      <div class="error-actions">
        <button class="action-btn primary" @click="retryLoading">
          <i class="fa fa-refresh"></i> 重试
        </button>
        <button class="action-btn secondary" @click="goBack">
          <i class="fa fa-arrow-left"></i> 返回课程列表
        </button>
      </div>
    </div>

    <!-- 课程不存在状态 -->
    <div class="error-state" v-else-if="!course">
      <i class="fa fa-search"></i>
      <h3>未找到课程</h3>
      <p>抱歉，您请求的课程不存在或已下架</p>
      <button class="action-btn primary" @click="goBack">
        <i class="fa fa-arrow-left"></i> 返回课程列表
      </button>
    </div>

    <div v-else class="course-content">
      <!-- 顶部面包屑导航 -->
      <div class="breadcrumb">
        <a href="/course/list" @click.prevent="goBack">课程列表</a>
        <span>&gt;</span>
        <span>{{ course.cName }}</span>
      </div>

      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 左侧：课程详情 -->
        <div class="left-column">
          <!-- 课程基本信息 -->
          <div class="info-card">
            <h2><i class="fa fa-info-circle"></i> 课程信息</h2>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">上课时间：</span>
                <span class="info-value">{{ formatFullCourseTime(course.cTime) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">课程时长：</span>
                <span class="info-value">{{ course.cDuration }} 分钟</span>
              </div>
              <div class="info-item">
                <span class="info-label">课程等级：</span>
                <span class="info-value">{{ course.cGrade }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">报名人数：</span>
                <span class="info-value">
                  {{ course.cCurrent }} / {{ course.cMax }}
                  <span class="capacity-progress">
                    <span class="progress-bar">
                      <span class="progress-fill" :style="{ width: `${getCapacityPercentage()}%` }"></span>
                    </span>
                  </span>
                </span>
              </div>
              <div class="info-item">
                <span class="info-label">课程状态：</span>
                <span class="info-value" :class="`status-text ${getStatusClass(course.c_run_status)}`">
                  {{ course.c_run_status }}
                </span>
              </div>
            </div>
          </div>

          <!-- 课程介绍 -->
          <div class="intro-card">
            <h2><i class="fa fa-book"></i> 课程介绍</h2>
            <div class="course-intro">
              <p>{{ course.cIntroduction || '暂无详细介绍' }}</p>
            </div>
          </div>

          <!-- 课程大纲 -->
          <div class="outline-card">
            <h2><i class="fa fa-list-alt"></i> 课程大纲</h2>
            <div class="course-outline">
              <ul>
                <li v-for="(item, index) in getCourseOutline(course.cName, course.cGrade)" :key="index" class="outline-item">
                  <span class="outline-number">{{ index + 1 }}</span>
                  <span class="outline-text">{{ item }}</span>
                </li>
              </ul>
            </div>
          </div>

          <!-- 相关课程推荐 -->
          <div class="related-courses-section">
            <h2><i class="fa fa-thumbs-up"></i> 推荐课程</h2>
            <div class="related-courses-grid">
              <div
                  v-for="relatedCourse in relatedCourses"
                  :key="relatedCourse.cId"
                  class="related-course-card"
                  @click="goToCourseDetail(relatedCourse.cId)"
              >
                <div class="related-course-img-container">
                  <img
                      :src="relatedCourse.cImage || `https://picsum.photos/seed/${relatedCourse.cId || related}/400/300`"
                      :alt="relatedCourse.cName"
                      class="related-course-img"
                      @load="onRelatedCourseImageLoad(relatedCourse.cId)"
                      @error="onRelatedCourseImageError(relatedCourse.cId)"
                      :class="{ 'loaded': relatedCourseImagesLoaded[relatedCourse.cId] }"
                  />
                  <div v-if="!relatedCourseImagesLoaded[relatedCourse.cId]" class="image-placeholder small">
                    <i class="fa fa-image"></i>
                  </div>
                </div>
                <div class="related-course-info">
                  <h3 class="related-course-name">{{ relatedCourse.cName }}</h3>
                  <p class="related-course-time">{{ formatCourseTime(relatedCourse.cTime) }}</p>
                  <span class="related-course-grade">{{ relatedCourse.cGrade }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：操作面板 -->
        <div class="right-column">
          <!-- 课程图片卡片 -->
          <div class="course-image-card">
            <div class="course-image-container">
              <img
                  :src="course.cImage || `https://picsum.photos/seed/${course.cId || course}/800/600`"
                  :alt="course.cName"
                  class="course-detail-img"
                  @load="onBannerLoad"
                  @error="onBannerError"
                  :class="{ 'loaded': bannerLoaded }"
              />
              <div v-if="!bannerLoaded" class="image-placeholder small">
                <i class="fa fa-image"></i>
              </div>
            </div>
          </div>

          <!-- 操作卡片 -->
          <div class="action-card">
            <div class="course-stats">
              <div class="stat-item">
                <i class="fa fa-calendar-check-o"></i>
                <span class="stat-label">下次开课</span>
                <span class="stat-value">{{ formatCourseDate(course.cTime) }}</span>
              </div>
              <div class="stat-item">
                <i class="fa fa-clock-o"></i>
                <span class="stat-label">开课时间</span>
                <span class="stat-value">{{ formatCourseStartTime(course.cTime) }}</span>
              </div>
              <div class="stat-item">
                <i class="fa fa-users"></i>
                <span class="stat-label">剩余名额</span>
                <span class="stat-value highlight">{{ course.cMax - course.cCurrent }}</span>
              </div>
            </div>

            <div class="reservation-actions">
              <button
                  v-if="canReserveCourse"
                  class="reserve-now-btn"
                  @click="openReservationModal"
              >
                <i class="fa fa-calendar-plus-o"></i>
                立即预约
              </button>
              <button
                  v-else
                  class="disabled-btn"
                  disabled
              >
                {{ getReservationButtonText }}
              </button>

              <button class="add-to-favorites-btn" @click="toggleFavorite">
                <i :class="isFavorite ? 'fa fa-heart' : 'fa fa-heart-o'"></i>
                {{ isFavorite ? '已收藏' : '收藏课程' }}
              </button>
            </div>

            <div class="course-reminder">
              <h3><i class="fa fa-bell"></i> 预约须知</h3>
              <ul>
                <li>请提前10分钟到达教室</li>
                <li>如需取消预约，请提前2小时操作</li>
                <li>累计3次未到场将影响后续预约</li>
                <li>请穿着舒适运动服装参加课程</li>
              </ul>
            </div>
          </div>

          <!-- 教练信息卡片 -->
          <div class="coach-card" v-if="course.cTId">
            <h2><i class="fa fa-user-circle"></i> 授课教练</h2>
            <div class="coach-info">
              <div class="coach-avatar">
                <img
                    :src="coach && coach.name === '林子健' ? '/src/assets/images/林子健.jpg' : (coach && coach.imageUrl ? coach.imageUrl : `https://picsum.photos/seed/${course.cTId || coach}/200/200`)"
                    alt="教练头像"
                    class="coach-img"
                    @load="onCoachImageLoad"
                    @error="onCoachImageError"
                    :class="{ 'loaded': coachImageLoaded }"
                />
                <div v-if="!coachImageLoaded" class="image-placeholder small">
                  <i class="fa fa-user"></i>
                </div>
              </div>
              <div class="coach-details">
                <h3 class="coach-name">{{ coach ? coach.name : '正在获取教练信息...' }}</h3>
                <p class="coach-specialty">专业领域：{{ coach ? (coach.specialty || '暂无信息') : '健身指导' }}</p>
                <p class="coach-experience">教学经验：{{ coach ? (coach.experience || '5年+') : '5年+' }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 预约弹窗 -->
    <CourseReservationModal
        v-model:visible="showReservationModal"
        :courseId="course?.cId"
        @reservation-success="onReservationSuccess"
    />

    <!-- 预约成功模态框 -->
    <div class="modal" v-if="showSuccessModal">
      <div class="modal-content">
        <div class="success-icon">
          <i class="fa fa-check-circle"></i>
        </div>
        <h3>预约成功！</h3>
        <p>您已成功预约{{ course.cName }}课程，请准时参加。</p>
        <div class="modal-actions">
          <button class="modal-btn" @click="closeSuccessModal">确定</button>
          <button class="modal-btn secondary" @click="goToReservations">查看我的预约</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { useUserStore } from '@/stores/auth';
import CourseReservationModal from '@/components/CourseReservationModal.vue';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 响应式数据
const course = ref(null);
const coach = ref(null); // 教练信息
const loading = ref(true);
const loadingProgress = ref(0); // 加载进度
const relatedCourses = ref([]);
const isFavorite = ref(false);
const showSuccessModal = ref(false);
const showReservationModal = ref(false); // 预约弹窗显示状态
const errorMessage = ref(''); // 错误信息

// 图片加载状态
const bannerLoaded = ref(false);
const coachImageLoaded = ref(false);
const relatedCourseImagesLoaded = ref({});

// 计算属性
const canReserveCourse = computed(() => {
  if (!course.value || !userStore.getIsLoggedIn || !userStore.userId) return false;
  if (course.value.c_run_status === '已结束') return false;
  if (course.value.cCurrent >= course.value.cMax) return false;

  const courseTime = new Date(course.value.cTime);
  const now = new Date();
  // 课程开始前2小时停止预约
  return courseTime > now && (courseTime - now) > 7200000; // 7200000毫秒 = 2小时
});

const getReservationButtonText = computed(() => {
  if (!userStore.getIsLoggedIn || !userStore.userId) return '请先登录';
  if (!course.value) return '加载中...';
  if (course.value.c_run_status === '已结束') return '课程已结束';
  if (course.value.cCurrent >= course.value.cMax) return '名额已满';

  const courseTime = new Date(course.value.cTime);
  const now = new Date();
  if (courseTime > now && (courseTime - now) <= 7200000) {
    return '预约已截止';
  }

  return '立即预约';
});

// 方法
const goBack = () => {
  router.push('/course/list');
};

const goToCourseDetail = (courseId) => {
  router.push(`/course/detail/${courseId}`);
};

const goToReservations = () => {
  router.push('/course/reservations');
};

const getStatusClass = (status) => {
  switch(status) {
    case '即将开始':
      return 'status-upcoming';
    case '进行中':
      return 'status-active';
    case '已结束':
      return 'status-inactive';
    default:
      return '';
  }
};

const formatCourseTime = (dateTime) => {
  if (!dateTime) return '';

  try {
    const date = new Date(dateTime);
    if (isNaN(date.getTime())) return dateTime;

    const now = new Date();
    const isToday = date.toDateString() === now.toDateString();
    const isTomorrow = new Date(now.getTime() + 86400000).toDateString() === date.toDateString();

    let dayText = '';
    if (isToday) {
      dayText = '今天';
    } else if (isTomorrow) {
      dayText = '明天';
    } else {
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      dayText = weekdays[date.getDay()];
    }

    return `${dayText} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  } catch (error) {
    console.error('时间格式化错误:', error);
    return dateTime;
  }
};

const formatFullCourseTime = (dateTime) => {
  if (!dateTime) return '';

  try {
    const date = new Date(dateTime);
    if (isNaN(date.getTime())) return dateTime;

    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      weekday: 'long'
    });
  } catch (error) {
    console.error('时间格式化错误:', error);
    return dateTime;
  }
};

const formatCourseDate = (dateTime) => {
  if (!dateTime) return '';

  try {
    const date = new Date(dateTime);
    if (isNaN(date.getTime())) return dateTime;

    return date.toLocaleDateString('zh-CN', {
      month: 'long',
      day: 'numeric',
      weekday: 'long'
    });
  } catch (error) {
    console.error('时间格式化错误:', error);
    return dateTime;
  }
};

const formatCourseStartTime = (dateTime) => {
  if (!dateTime) return '';

  try {
    const date = new Date(dateTime);
    if (isNaN(date.getTime())) return dateTime;

    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    console.error('时间格式化错误:', error);
    return dateTime;
  }
};

const getCapacityPercentage = () => {
  if (!course.value || course.value.cMax === 0) return 0;
  return Math.min((course.value.cCurrent / course.value.cMax) * 100, 100);
};

const getCourseOutline = (courseName, grade) => {
  // 根据课程名称和等级生成模拟大纲
  const baseOutline = [
    '课程介绍与热身（10分钟）',
    '基础动作讲解与练习（20分钟）',
    '核心训练环节（20-30分钟）',
    '放松与拉伸（10-15分钟）',
    '课程总结与建议（5分钟）'
  ];

  // 根据课程等级调整大纲内容
  if (grade === '初级') {
    return baseOutline.map(item => `[初级友好] ${item}`);
  } else if (grade === '高级') {
    return baseOutline.map(item => `[强度较高] ${item}`);
  }

  return baseOutline;
};

const toggleFavorite = () => {
  if (!userStore.isLoggedIn) {
    alert('请先登录后再收藏课程');
    router.push('/auth/login');
    return;
  }

  isFavorite.value = !isFavorite.value;
  alert(isFavorite.value ? '课程已添加到收藏！' : '已取消收藏');
};

// 修改预约课程方法 - 打开预约弹窗
const openReservationModal = () => {
  if (!userStore.getIsLoggedIn || !userStore.userId) {
    alert('请先登录后再预约课程');
    router.push('/auth/login');
    return;
  }

  showReservationModal.value = true;
};

const closeSuccessModal = () => {
  showSuccessModal.value = false;
};

// 预约成功回调
const onReservationSuccess = () => {
  // 重新加载课程详情以更新人数
  loadCourseDetail();
  showSuccessModal.value = true;
};

// 获取教练信息
const fetchCoachById = async (coachId) => {
  if (!coachId) return;

  try {
    // 尝试获取单个教练信息
    const response = await axios.get(`/api/coaches/${coachId}`);

    if (response.data && response.data.code === 200) {
      coach.value = response.data.data;
    } else {
      // 如果单个教练API失败，尝试获取所有教练并筛选
      const allCoachesResponse = await axios.get('/api/coaches/all');
      if (allCoachesResponse.data && allCoachesResponse.data.code === 200) {
        const coachData = allCoachesResponse.data.data.find(c => c.id === coachId);
        if (coachData) {
          coach.value = coachData;
        }
      }
    }
  } catch (error) {
    console.error('获取教练信息失败:', error);
    // 即使出错也不影响页面显示
  }
};

// 图片加载处理
const onBannerLoad = () => {
  bannerLoaded.value = true;
};

const onBannerError = () => {
  bannerLoaded.value = true; // 即使出错也显示占位符
};

const onCoachImageLoad = () => {
  coachImageLoaded.value = true;
};

const onCoachImageError = () => {
  coachImageLoaded.value = true; // 即使出错也显示占位符
};

const onRelatedCourseImageLoad = (courseId) => {
  relatedCourseImagesLoaded.value[courseId] = true;
};

const onRelatedCourseImageError = (courseId) => {
  relatedCourseImagesLoaded.value[courseId] = true; // 即使出错也显示占位符
};

const loadCourseDetail = async () => {
  // 添加详细的调试日志，确保我们能追踪路由参数获取过程
  console.log('当前路由对象:', route);
  console.log('路由参数对象:', route.params);

  // 安全地获取课程ID，确保即使参数不存在也有合理的默认值
  const courseId = route.params.id || '1'; // 默认使用ID 1
  console.log(`加载课程详情，课程ID: ${courseId}`);

  loading.value = true;
  errorMessage.value = '';
  loadingProgress.value = 0;

  // 重置图片加载状态
  bannerLoaded.value = false;
  coachImageLoaded.value = false;
  relatedCourseImagesLoaded.value = {};

  // 模拟加载进度
  const progressInterval = setInterval(() => {
    if (loadingProgress.value < 90) {
      loadingProgress.value += Math.random() * 20;
    }
  }, 300);

  try {
    // 尝试获取课程详情
    const response = await axios.get(`/api/courses/${courseId}`);

    if (response.data) {
      course.value = response.data;
    } else {
      // 如果API调用失败，使用模拟数据
      console.warn('API返回空数据，使用模拟数据');
      course.value = getMockCourseDetail(courseId);
    }

    // 获取教练信息
    if (course.value && course.value.cTId) {
      await fetchCoachById(course.value.cTId);
    }
  } catch (error) {
    console.error('获取课程详情失败:', error);
    // 使用模拟数据作为降级方案
    course.value = getMockCourseDetail(courseId);

    // 显示友好的错误提示（但不阻断用户体验，因为已经使用了模拟数据）
    if (!course.value) {
      errorMessage.value = '无法加载课程详情，请稍后再试';
    }

    // 即使课程加载失败，也尝试获取教练信息
    if (course.value && course.value.cTId) {
      await fetchCoachById(course.value.cTId);
    }
  } finally {
    clearInterval(progressInterval);
    loadingProgress.value = 100;
    // 稍微延迟以让用户看到加载完成
    setTimeout(() => {
      loading.value = false;
    }, 300);
  }
};

// 重试加载数据
const retryLoading = async () => {
  errorMessage.value = '';
  await loadCourseDetail();
  await loadRelatedCourses();
};

const loadRelatedCourses = async () => {
  try {
    // 尝试获取相关课程
    const response = await axios.get('/api/courses/available');

    if (response.data && Array.isArray(response.data)) {
      // 过滤掉当前课程，获取其他符合条件的课程作为推荐
      const filteredCourses = response.data
          .filter(c => c.cId !== course.value?.cId && c.cStatus === 1);

      // 确保至少有一些推荐课程
      if (filteredCourses.length > 0) {
        relatedCourses.value = filteredCourses.slice(0, 3); // 最多显示3个推荐课程
      } else {
        // 如果没有足够的推荐课程，使用模拟数据补充
        relatedCourses.value = getMockRelatedCourses();
      }
    } else {
      // 如果API调用失败，使用模拟数据
      relatedCourses.value = getMockRelatedCourses();
    }
  } catch (error) {
    console.error('获取相关课程失败:', error);
    // 使用模拟数据
    relatedCourses.value = getMockRelatedCourses();
  }
};

const getMockCourseDetail = (courseId) => {
  const now = new Date();
  const tomorrow = new Date(now.getTime() + 86400000);
  const dayAfterTomorrow = new Date(now.getTime() + 2 * 86400000);

  // 扩展课程类型数据，包含所有可能的课程ID
  const courseTypes = [
    {
      id: 1,
      name: '瑜伽基础课',
      grade: '初级',
      intro: '本课程适合瑜伽初学者，通过基础体式的练习，帮助学员建立正确的瑜伽姿势概念，提高身体柔韧性，缓解压力，改善睡眠质量。课程内容包括基础呼吸法、热身动作、基础体式练习和冥想放松。',
      time: tomorrow.toISOString(),
      duration: 60
    },
    {
      id: 2,
      name: '高强度间歇训练',
      grade: '高级',
      intro: '这是一节高强度的间歇训练课程，结合有氧和力量训练，帮助学员快速燃脂、增强心肺功能和肌肉耐力。课程包括热身、高强度训练循环、核心训练和放松拉伸四个部分，适合有一定运动基础的健身爱好者。',
      time: new Date(now.getTime() + 1.5 * 86400000).toISOString(),
      duration: 45
    },
    {
      id: 3,
      name: '有氧拳击',
      grade: '中级',
      intro: '有氧拳击课程将拳击技巧与有氧运动相结合，既能锻炼全身肌肉，又能提高心肺功能。课程内容包括基本拳击姿势、拳法组合、步法练习和反应训练。无需拳击经验，教练将全程指导，适合各个年龄段的健身爱好者。',
      time: new Date(now.getTime() + 3 * 86400000).toISOString(),
      duration: 60
    },
    {
      id: 4,
      name: '普拉提核心训练',
      grade: '中级',
      intro: '普拉提是一种专注于核心力量、柔韧性和姿态改善的训练方法。本课程通过精准的动作练习，帮助学员强化核心肌群，改善身体姿态，增加身体控制力。适合各个年龄段的健身爱好者，尤其适合长期久坐办公室的人群。',
      time: new Date(now.getTime() + 2 * 86400000).toISOString(),
      duration: 50
    },
    {
      id: 5,
      name: '力量塑形',
      grade: '中级',
      intro: '本课程专注于力量训练和肌肉塑形，通过各种器械和自由重量练习，帮助学员增强肌肉力量，塑造完美体型。课程内容包括上肢训练、下肢训练、核心训练和全身综合训练，适合有一定训练基础的健身爱好者。',
      time: new Date(now.getTime() + 2.5 * 86400000).toISOString(),
      duration: 60
    },
    {
      id: 6,
      name: '舞蹈健身课',
      grade: '初级',
      intro: '这是一节充满活力的舞蹈健身课，融合了现代舞、爵士舞和街舞元素。通过有趣的舞蹈动作，帮助学员在欢乐的氛围中燃烧卡路里，提高协调性和节奏感。无需舞蹈基础，教练将分解动作教学，适合所有年龄段的健身爱好者。',
      time: new Date(now.getTime() + 4 * 86400000).toISOString(),
      duration: 55
    },
    {
      id: 7,
      name: '功能性训练',
      grade: '高级',
      intro: '功能性训练是一种模拟日常生活动作的综合训练方法，旨在提高身体在日常活动和运动中的表现能力。课程内容包括多关节运动、平衡训练、协调性训练和爆发力训练，适合有较高运动基础的健身爱好者。',
      time: new Date(now.getTime() + 5 * 86400000).toISOString(),
      duration: 50
    },
    {
      id: 8,
      name: '瑜伽冥想课',
      grade: '初级',
      intro: '本课程专注于瑜伽冥想和呼吸练习，帮助学员放松身心，减轻压力，改善专注力和睡眠质量。课程内容包括呼吸技巧、冥想练习、瑜伽休息术和正念训练，适合所有年龄段和健身水平的人群。',
      time: new Date(now.getTime() + 0.5 * 86400000).toISOString(),
      duration: 45
    },
    {
      id: 9,
      name: '核心强化训练',
      grade: '中级',
      intro: '核心强化训练专注于腹部、腰部和臀部肌肉群的锻炼，帮助学员塑造完美腰腹线条，增强核心稳定性。课程内容包括多种平板支撑变化、仰卧起坐、侧腰训练和臀部训练，适合所有希望改善腰腹线条的健身爱好者。',
      time: dayAfterTomorrow.toISOString(),
      duration: 40
    },
    {
      id: 10,
      name: '拉伸放松课',
      grade: '初级',
      intro: '本课程专注于全身各部位的拉伸和放松练习，帮助学员增加身体柔韧性，缓解肌肉紧张，预防运动损伤。课程内容包括静态拉伸、动态拉伸、筋膜放松和呼吸放松技巧，适合所有健身水平的人群，尤其是喜欢高强度训练的健身爱好者。',
      time: new Date(now.getTime() + 1 * 86400000).toISOString(),
      duration: 50
    }
  ];

  // 尝试根据ID找到对应的课程类型，如果不存在则创建一个自定义课程
  const parsedId = parseInt(courseId);
  const courseType = courseTypes.find(c => c.id === parsedId);

  // 模拟教练数据
  const mockCoaches = [
    { id: 1, name: '张明', specialty: '瑜伽指导', experience: '8年+' },
    { id: 2, name: '李华', specialty: '高强度训练', experience: '6年+' },
    { id: 3, name: '王芳', specialty: '有氧拳击', experience: '5年+' },
    { id: 4, name: '赵强', specialty: '力量训练', experience: '7年+' },
    { id: 5, name: '陈静', specialty: '普拉提', experience: '6年+' }
  ];

  // 随机选择一个教练
  const randomCoachId = Math.floor(Math.random() * 5) + 1;
  const selectedCoach = mockCoaches.find(c => c.id === randomCoachId);

  // 直接设置教练信息，确保在模拟环境下也能显示
  if (selectedCoach) {
    coach.value = selectedCoach;
  }

  // 如果找到匹配的课程类型，使用其信息
  if (courseType) {
    return {
      cId: parsedId,
      cName: courseType.name,
      cGrade: courseType.grade,
      cIntroduction: courseType.intro,
      cTime: courseType.time,
      cDuration: courseType.duration,
      cMax: 20,
      cCurrent: Math.floor(Math.random() * 15),
      cStatus: 1,
      c_run_status: '即将开始',
      cImage: `https://picsum.photos/seed/${courseType.id}/800/600`,
      cTId: randomCoachId // 使用随机教练ID
    };
  }

  // 如果没有找到匹配的课程类型，创建一个通用的自定义课程
  return {
    cId: parsedId,
    cName: `自定义课程 ${parsedId}`,
    cGrade: '初级',
    cIntroduction: '这是一个根据您的选择动态生成的课程。课程内容丰富多样，由专业教练指导，适合各级健身爱好者参与。',
    cTime: tomorrow.toISOString(),
    cDuration: 60,
    cMax: 20,
    cCurrent: Math.floor(Math.random() * 15),
    cStatus: 1,
    c_run_status: '即将开始',
    cImage: `https://picsum.photos/seed/${parsedId}/800/600`,
    cTId: 1 // 默认使用教练ID 1
  };
};

const getMockRelatedCourses = () => {
  const now = new Date();
  const courses = [
    {
      cId: 4,
      cName: '普拉提核心训练',
      cGrade: '中级',
      cTime: new Date(now.getTime() + 2 * 86400000).toISOString(),
      cImage: 'https://picsum.photos/seed/4/400/300'
    },
    {
      cId: 5,
      cName: '力量塑形',
      cGrade: '中级',
      cTime: new Date(now.getTime() + 3 * 86400000).toISOString(),
      cImage: 'https://picsum.photos/seed/5/400/300'
    },
    {
      cId: 6,
      cName: '舞蹈健身课',
      cGrade: '初级',
      cTime: new Date(now.getTime() + 4 * 86400000).toISOString(),
      cImage: 'https://picsum.photos/seed/6/400/300'
    },
    {
      cId: 7,
      cName: '功能性训练',
      cGrade: '高级',
      cTime: new Date(now.getTime() + 5 * 86400000).toISOString(),
      cImage: 'https://picsum.photos/seed/7/400/300'
    }
  ];

  // 过滤掉当前课程并随机排序
  return courses
      .filter(c => c.cId !== course.value?.cId)
      .sort(() => Math.random() - 0.5)
      .slice(0, 3);
};

// 组件挂载时加载数据
onMounted(async () => {
  await loadCourseDetail();
  await loadRelatedCourses();
});

// 监听路由参数变化，确保当ID改变时重新加载数据
import { watch } from 'vue';

// 改进的路由参数变化监听，确保组件状态被完全重置且数据被正确加载
watch(
    () => route.params,
    async (newParams, oldParams) => {
      // 监听整个params对象，确保捕获所有变化
      console.log(`路由参数变化: 从`, oldParams, `到`, newParams);
      const newId = newParams.id || '1'; // 安全获取ID

      // 完全重置所有状态
      course.value = null;
      loading.value = true;
      loadingProgress.value = 0;
      relatedCourses.value = [];
      isFavorite.value = false;
      errorMessage.value = '';
      showSuccessModal.value = false;
      showReservationModal.value = false;

      // 强制等待DOM更新
      await nextTick();

      // 重新加载数据
      await loadCourseDetail();
      await loadRelatedCourses();

      console.log(`已加载课程ID: ${newId} 的详情`);
    },
    { immediate: true, deep: true } // 确保立即执行且深度监听
);
</script>

<style scoped>
.course-detail-page {
  min-height: 100vh;
  background-color: #1a202c;
  background-image:
      radial-gradient(rgba(246, 173, 85, 0.05) 2px, transparent 2px),
      radial-gradient(rgba(45, 55, 72, 0.03) 2px, transparent 2px);
  background-size: 50px 50px;
  background-position: 0 0, 25px 25px;
  position: relative;
  overflow: hidden;
  padding-bottom: 40px;
}

.loading-state,
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
  color: #cbd5e0;
  text-align: center;
  padding: 40px 20px;
  background: rgba(15, 23, 42, 0.8);
  backdrop-filter: blur(25px);
  margin: 20px;
  border-radius: 12px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.08);
}

.loading-state h3,
.error-state h3 {
  margin: 20px 0 10px;
  font-size: 1.5rem;
  color: #f8fafc;
}

.loading-spinner {
  width: 60px;
  height: 60px;
  border: 6px solid rgba(255, 255, 255, 0.1);
  border-top: 6px solid #f6ad55;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-progress {
  width: 200px;
  height: 8px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  margin-top: 20px;
  overflow: hidden;
}

.loading-bar {
  height: 100%;
  background: linear-gradient(90deg, #f6ad55, #ed8936);
  border-radius: 4px;
  transition: width 0.3s ease;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { opacity: 0.8; }
  50% { opacity: 1; }
  100% { opacity: 0.8; }
}

.error-state i {
  font-size: 64px;
  color: #f6ad55;
  margin-bottom: 20px;
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: scale(0.8); }
  to { opacity: 1; transform: scale(1); }
}

.error-actions {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.action-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-btn.primary {
  background: linear-gradient(135deg, #f6ad55, #ed8936);
  color: white;
}

.action-btn.primary:hover {
  background: linear-gradient(135deg, #ed8936, #dd7714);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(246, 173, 85, 0.4);
}

.action-btn.secondary {
  background: rgba(255, 255, 255, 0.1);
  color: #cbd5e0;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.action-btn.secondary:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.back-btn {
  margin-top: 20px;
  padding: 10px 20px;
  background: linear-gradient(135deg, #f6ad55, #ed8936);
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.breadcrumb {
  background: rgba(15, 23, 42, 0.8);
  backdrop-filter: blur(25px);
  padding: 15px 20px;
  margin-bottom: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  font-size: 0.9rem;
  color: #cbd5e0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.breadcrumb a {
  color: #f6ad55;
  text-decoration: none;
}

.breadcrumb a:hover {
  text-decoration: underline;
}

.breadcrumb span {
  margin: 0 10px;
}

.course-header {
  margin-bottom: 30px;
}

.course-image-card {
  background: rgba(15, 23, 42, 0.8);
  backdrop-filter: blur(25px);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.4);
  margin-bottom: 20px;
  border: 1px solid rgba(255, 255, 255, 0.08);
}

.course-image-container {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.05);
}

.course-detail-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: opacity 0.3s ease;
  opacity: 0;
}

.course-detail-img.loaded {
  opacity: 1;
}

.image-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.05);
  color: #94a3b8;
  font-size: 1rem;
}

.image-placeholder.small {
  font-size: 1rem;
}

.image-placeholder i {
  font-size: 2rem;
  margin-bottom: 10px;
}

.image-placeholder.small i {
  font-size: 1.5rem;
  margin-bottom: 0;
}

.course-title-section {
  margin-bottom: 30px;
  padding: 0 20px;
}

.course-title {
  font-size: 2.5rem;
  margin-bottom: 20px;
  color: #f8fafc;
  line-height: 1.2;
}

.course-meta-header {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.status-badge,
.grade-badge,
.duration-badge {
  padding: 5px 12px;
  border-radius: 20px;
  font-size: 0.9rem;
  font-weight: 600;
  background: rgba(255, 255, 255, 0.1);
  color: #f8fafc;
}

.status-upcoming {
  background: linear-gradient(135deg, #48bb78, #38a169) !important;
}

.status-active {
  background: linear-gradient(135deg, #4299e1, #3182ce) !important;
}

.status-inactive {
  background: linear-gradient(135deg, #a0aec0, #718096) !important;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
  padding: 0 20px;
}

.left-column,
.right-column {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-card,
.intro-card,
.outline-card,
.action-card,
.coach-card {
  background: rgba(15, 23, 42, 0.8);
  backdrop-filter: blur(25px);
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.08);
}

.info-card h2,
.intro-card h2,
.outline-card h2,
.coach-card h2 {
  margin-bottom: 20px;
  color: #f8fafc;
  font-size: 1.4rem;
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-card h2 i,
.intro-card h2 i,
.outline-card h2 i,
.coach-card h2 i {
  color: #f6ad55;
}

.info-grid {
  display: grid;
  gap: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-weight: 500;
  color: #94a3b8;
}

.info-value {
  font-weight: 600;
  color: #f8fafc;
}

.capacity-progress {
  margin-left: 10px;
}

.progress-bar {
  display: inline-block;
  width: 100px;
  height: 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  overflow: hidden;
  vertical-align: middle;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #f6ad55, #ed8936);
  transition: width 0.3s;
}

.status-text {
  padding: 3px 10px;
  border-radius: 15px;
  font-size: 0.85rem;
  font-weight: 500;
  color: white;
}

.course-intro {
  line-height: 1.8;
  color: #cbd5e0;
}

.course-outline ul {
  list-style: none;
  padding: 0;
}

.outline-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.outline-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.outline-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  background: linear-gradient(135deg, #f6ad55, #ed8936);
  color: white;
  border-radius: 50%;
  font-weight: 600;
  font-size: 0.9rem;
  flex-shrink: 0;
}

.outline-text {
  line-height: 1.6;
  color: #cbd5e0;
}

.course-stats {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 25px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
}

.stat-item i {
  color: #f6ad55;
  font-size: 1.2rem;
  width: 24px;
  text-align: center;
}

.stat-label {
  color: #94a3b8;
  font-size: 0.9rem;
}

.stat-value {
  margin-left: auto;
  font-weight: 600;
  color: #f8fafc;
}

.stat-value.highlight {
  color: #f6ad55;
  font-size: 1.1rem;
}

.reservation-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 25px;
}

.reserve-now-btn,
.add-to-favorites-btn,
.disabled-btn {
  padding: 15px;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.reserve-now-btn {
  background: linear-gradient(135deg, #f6ad55, #ed8936);
  color: white;
}

.reserve-now-btn:hover {
  background: linear-gradient(135deg, #ed8936, #dd7714);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(246, 173, 85, 0.4);
}

.add-to-favorites-btn {
  background: rgba(255, 255, 255, 0.1);
  color: #f8fafc;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.add-to-favorites-btn:hover {
  background: rgba(255, 255, 255, 0.15);
}

.disabled-btn {
  background: rgba(255, 255, 255, 0.05);
  color: #94a3b8;
  cursor: not-allowed;
}

.course-reminder {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 20px;
}

.course-reminder h3 {
  margin-bottom: 15px;
  color: #f8fafc;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1.1rem;
}

.course-reminder h3 i {
  color: #f6ad55;
}

.course-reminder ul {
  padding-left: 20px;
  color: #cbd5e0;
}

.course-reminder li {
  margin-bottom: 8px;
  line-height: 1.5;
}

.coach-info {
  display: flex;
  gap: 20px;
  align-items: center;
}

.coach-avatar {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid #f6ad55;
  flex-shrink: 0;
}

.coach-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: opacity 0.3s ease;
  opacity: 0;
}

.coach-img.loaded {
  opacity: 1;
}

.coach-details h3 {
  margin-bottom: 5px;
  color: #f8fafc;
}

.coach-specialty,
.coach-experience {
  color: #cbd5e0;
  font-size: 0.9rem;
  margin-bottom: 3px;
}

.related-courses-section {
  margin-top: 30px;
  padding: 25px;
  background: rgba(15, 23, 42, 0.8);
  backdrop-filter: blur(25px);
  border-radius: 12px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.08);
}

.related-courses-section h2 {
  margin-bottom: 25px;
  color: #f8fafc;
  font-size: 1.8rem;
  display: flex;
  align-items: center;
  gap: 10px;
}

.related-courses-section h2 i {
  color: #f6ad55;
}

.related-courses-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.related-course-card {
  background: rgba(15, 23, 42, 0.8);
  backdrop-filter: blur(25px);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.4);
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  border: 1px solid rgba(255, 255, 255, 0.08);
}

.related-course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 35px 60px rgba(0, 0, 0, 0.5);
}

.related-course-img-container {
  position: relative;
  width: 100%;
  height: 160px;
  overflow: hidden;
}

.related-course-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: opacity 0.3s ease;
  opacity: 0;
}

.related-course-img.loaded {
  opacity: 1;
}

.related-course-info {
  padding: 15px;
}

.related-course-name {
  margin-bottom: 8px;
  color: #f8fafc;
  font-size: 1.1rem;
  line-height: 1.3;
  height: 2.6em;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.related-course-time {
  margin-bottom: 8px;
  color: #cbd5e0;
  font-size: 0.9rem;
}

.related-course-grade {
  display: inline-block;
  padding: 2px 10px;
  background: rgba(246, 173, 85, 0.2);
  color: #f6ad55;
  border-radius: 12px;
  font-size: 0.85rem;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.modal-content {
  background: rgba(15, 23, 42, 0.95);
  backdrop-filter: blur(25px);
  border-radius: 12px;
  padding: 30px;
  max-width: 400px;
  width: 90%;
  text-align: center;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.success-icon {
  margin-bottom: 20px;
}

.success-icon i {
  font-size: 48px;
  color: #48bb78;
}

.modal-content h3 {
  margin-bottom: 15px;
  color: #f8fafc;
}

.modal-content p {
  margin-bottom: 25px;
  color: #cbd5e0;
  line-height: 1.6;
}

.modal-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.modal-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.modal-btn:first-child {
  background: linear-gradient(135deg, #f6ad55, #ed8936);
  color: white;
}

.modal-btn.secondary {
  background: rgba(255, 255, 255, 0.1);
  color: #f8fafc;
}

.modal-btn.secondary:hover {
  background: rgba(255, 255, 255, 0.15);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-content {
    grid-template-columns: 1fr;
  }

  .right-column {
    order: -1;
  }
}

@media (max-width: 768px) {
  .course-banner {
    height: 300px;
    margin: 0 10px;
  }

  .banner-container {
    min-height: 300px;
  }

  .course-banner-img {
    min-height: 300px;
  }

  .course-overlay {
    padding: 20px;
  }

  .course-title {
    font-size: 2rem;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }

  .coach-info {
    flex-direction: column;
    text-align: center;
  }

  .related-courses-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }
}

@media (max-width: 480px) {
  .course-banner {
    height: 200px;
  }

  .banner-container {
    min-height: 200px;
  }

  .course-banner-img {
    min-height: 200px;
  }

  .course-title {
    font-size: 1.5rem;
  }

  .course-meta-banner {
    flex-direction: column;
    gap: 8px;
  }

  .modal-actions {
    flex-direction: column;
  }
}
</style>